package com.guaju.yueshangLife.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsoluteLayout;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.base.BaseActivity;
import com.guaju.yueshangLife.base.BaseFragmentActivity;
import com.guaju.yueshangLife.databinding.ActivityMainBinding;
import com.guaju.yueshangLife.fragment.CartFragment;
import com.guaju.yueshangLife.fragment.HomeFragment;
import com.guaju.yueshangLife.fragment.MineFragment;
import com.guaju.yueshangLife.fragment.CategoryFragment;
import com.guaju.yueshangLife.global.BaseApplication;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.net.NetworkUtil;
import com.guaju.yueshangLife.utils.AppManager;
import com.guaju.yueshangLife.utils.ToastUtil;
import com.guaju.yueshangLife.utils.Utils;
import com.guaju.yueshangLife.viewmodel.MainVM;
import com.lljjcoder.style.citylist.Toast.ToastUtils;

import java.util.ArrayList;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;

public class MainActivity extends BaseFragmentActivity {
    public static final String TAB_POSITION = "position";
    private static final int REQUEST_PERMISSION = 1000;
    private ActivityMainBinding binding;
    private long firstTime;
    private ArrayList<Fragment> mFragmentList;
    private MainVM mainVM;
    private FragmentManager fm;
    private FragmentTransaction ft;
    private LayoutInflater layoutInflater;
    private View fake_status_bar;
    private int tab_position = 0;
    private static int back_tab_position = 0;
    private View news_loading;

    public void setTab_position(int back_tab_position) {
        this.back_tab_position = back_tab_position;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseApplication.getInstance().setMainActivity(this);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        addProgressPic();
        initView();
        setListener();

    }

    public void hideProgressPic() {
        if (news_loading != null) {
            news_loading.setVisibility(View.GONE);
        }
    }

    public void addProgressPic() {
        news_loading = View.inflate(MainActivity.this, R.layout.loading, null);
        news_loading.setLayoutParams(new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.MATCH_PARENT, AbsoluteLayout.LayoutParams.MATCH_PARENT, 0, 0));
        Bitmap mBgBitmap = Utils.readBitMap(MainActivity.this, R.drawable.home_loading);
        news_loading.setBackgroundDrawable(new BitmapDrawable(mBgBitmap));
        binding.rlContainer.addView(news_loading);
        news_loading.setVisibility(View.VISIBLE);
    }

    private void setListener() {

    }

    private void initView() {
        //一体栏
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.home_background));
        //动态权限申请
        PermissionGen.with(MainActivity.this)
                .addRequestCode(REQUEST_PERMISSION)
                .permissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        android.Manifest.permission.READ_PHONE_STATE
                )
                .request();
        mainVM = new MainVM();
        initFragment();
        binding.setViewmodel(mainVM);
        Intent intent = getIntent();
        if (intent != null) {
            tab_position = intent.getIntExtra(TAB_POSITION, -1);
            if (-1 != tab_position) {
                switchFragmentTab(tab_position);
            }
        }
        if (-1 == tab_position) {
            switchFragmentTab(back_tab_position);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();


        showNetError();


    }

    private void switchFragmentTab(int tab_position) {
        if (tab_position == 0)
            switchToHomeFragment();
        else if (tab_position == 1)
            switchToCateFragment();
        else if (tab_position == 2)
            switchToCartFragment();
        else if (tab_position == 3)
            switchToMineFragment();
        else switchToHomeFragment();
    }

    private void initFragment() {
        layoutInflater = LayoutInflater.from(this);
        fake_status_bar = layoutInflater.inflate(R.layout.fake_status_bar, null, false);
        mFragmentList = new ArrayList<>();
        mFragmentList.add(new HomeFragment());
        mFragmentList.add(new CategoryFragment());
        mFragmentList.add(new CartFragment());
        mFragmentList.add(new MineFragment());
        fm = getSupportFragmentManager();
        ft = fm.beginTransaction();
        ft.add(R.id.fl_container, mFragmentList.get(0));
        ft.add(R.id.fl_container, mFragmentList.get(1));
        ft.add(R.id.fl_container, mFragmentList.get(2));
        ft.add(R.id.fl_container, mFragmentList.get(3));
        ft.hide(mFragmentList.get(1));
        ft.hide(mFragmentList.get(2));
        ft.hide(mFragmentList.get(3));
        ft.commit();

        mainVM.setBottomClickedListener(new MainVM.OnBottomClickListener() {
            @Override
            public void onBottomClick(int index) {
                switch (index) {
                    case 0:
                        switchToHomeFragment();
                        break;
                    case 1:
                        switchToCateFragment();
                        break;
                    case 2:
                        switchToCartFragment();
                        break;
                    case 3:
                        switchToMineFragment();
                        break;
                    default:
                        break;

                }
            }
        });

    }

    public void switchToMineFragment() {
        ft = fm.beginTransaction();
        hideAll(ft);
        binding.searchbar.setVisibility(View.GONE);
        resetAll();
        binding.mine.setChecked(true);
        setTab_position(3);
        ft.show(mFragmentList.get(3));
        ft.commit();
    }

    public void switchToCartFragment() {
        ft = fm.beginTransaction();
        hideAll(ft);
        binding.searchbar.setVisibility(View.GONE);
        setTab_position(2);
        resetAll();
        binding.cart.setChecked(true);
        ft.show(mFragmentList.get(2));
        ft.commit();
    }

    public void switchToCateFragment() {
        ft = fm.beginTransaction();
        hideAll(ft);
        binding.searchbar.setVisibility(View.VISIBLE);
        ft.show(mFragmentList.get(1));
        setTab_position(1);
        resetAll();
        binding.category.setChecked(true);
        ft.commit();
    }

    public void switchToHomeFragment() {
        ft = fm.beginTransaction();
        hideAll(ft);
        binding.searchbar.setVisibility(View.VISIBLE);
        setTab_position(0);
        resetAll();
        binding.home.setChecked(true);
        ft.show(mFragmentList.get(0));
        ft.commit();
    }

    private void resetAll() {
        binding.home.reset();
        binding.cart.reset();
        binding.category.reset();
        binding.mine.reset();

    }

    private void hideAll(FragmentTransaction ft) {
        if (ft != null) {
            ft.hide(mFragmentList.get(0));
            ft.hide(mFragmentList.get(1));
            ft.hide(mFragmentList.get(2));
            ft.hide(mFragmentList.get(3));
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionFail(requestCode = REQUEST_PERMISSION)
    public void doFailSomething() {
        Toast.makeText(this, "为了您的用户体验，请您开启权限", Toast.LENGTH_SHORT).show();
        PermissionGen.with(MainActivity.this)
                .addRequestCode(REQUEST_PERMISSION)
                .permissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        android.Manifest.permission.READ_PHONE_STATE
                )
                .request();
    }

    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            ToastUtil.show("再按一次退出程序");
            firstTime = secondTime;
        } else {
            finish();
            AppManager.getAppManager().finishAllActivity();
            ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
            manager.killBackgroundProcesses(getPackageName());
        }
    }


}
